/**
* 版权声明：厦门睿商网络科技有限公司 版权所有 违者必究
* 日    期：2020-08-06
*/
package com.rzico.order.controller.member;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.rzico.annotation.Log;
import com.rzico.base.BaseController;
import com.rzico.base.CommResult;
import com.rzico.basics.entity.CouponCode;
import com.rzico.basics.entity.Enterprise;
import com.rzico.basics.entity.Member;
import com.rzico.basics.service.CouponCodeService;
import com.rzico.basics.service.EnterpriseService;
import com.rzico.basics.service.MemberService;
import com.rzico.entity.PageResult;
import com.rzico.entity.Pageable;
import com.rzico.order.entity.GiftCard;
import com.rzico.order.entity.Order;
import com.rzico.order.enumx.OrderShippingStatusEnum;
import com.rzico.order.enumx.OrderStatusEnum;
import com.rzico.order.service.AskforService;
import com.rzico.order.service.GiftCardService;
import com.rzico.order.service.OrderService;
import com.rzico.util.RedisHandler;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 礼品卡控制层
 *
 * @author Rzico Boot
 * @version 1.0
 * @date 2020-08-06
 */
@Api(description = "礼品卡接口")
@RestController
@RequestMapping("/member/giftCard")
public class GiftCardMemberController extends BaseController {

    @Autowired
    private GiftCardService giftCardService;

    @Autowired
    protected MemberService memberService;

    @Autowired
    private EnterpriseService enterpriseService;

    @Autowired
    private OrderService orderService;

    @Autowired
    private AskforService askforService;

    @Autowired
    private RedisHandler redisHandler;



    /**
     * 分页查询礼品卡
     *
     * @return
     */
    @ApiOperation("分页查询礼品卡")
    @GetMapping("/list")
    @ApiImplicitParams(
            {
                    @ApiImplicitParam(name = "memberId", value = "创建人", dataType = "Long", paramType = "query") ,
                    @ApiImplicitParam(name = "receiverId", value = "接收人", dataType = "Long", paramType = "query")
            })
    public CommResult<GiftCard> list(Long memberId, Long receiverId, Pageable pageable) {
        Map<String, Object> params = new HashMap<String, Object>();
        params = buildSortField(params, pageable);

        Member member = memberService.getCurrent();

        if (memberId!=null){
            params.put("memberId", member.getId());
        } else {
            params.put("receiverId", member.getId());
        }

        Page<Object> startPage = PageHelper.startPage(pageable.getPageNum(), pageable.getPageSize());
        List<GiftCard> list = giftCardService.selectList(params);
        PageResult<GiftCard> pageResult = new PageResult<GiftCard>(list, startPage.getTotal(), pageable);
        return CommResult.success(pageResult);
    }


    /**
     * 创建礼卡
     *
     * @param orderId
     * @return
     */
    @Log(desc = "创建礼卡", type = Log.LOG_TYPE.ADD)
    @ApiOperation("创建礼卡")
    @PostMapping("/create")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orderId", value = "订单ID", dataType = "Long", paramType = "query")
    })
    public CommResult<GiftCard> create(Long orderId) {

        String key = "order-"+String.valueOf(orderId);
        String value = key;
        if (key!=null) {
            while (!redisHandler.lock(key, value)) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }

        try {

            Map<String, Object> data = new HashMap<>();
            data.put("orderId", orderId);
            data.put("askfored", true);
            Integer w = askforService.selectRowCount(data);

            if (w > 0) {
                return CommResult.error("订单有退款");
            }


            Order order = orderService.selectByPrimaryKey(orderId);

            if (!order.getOrderStatus().equals(OrderStatusEnum.ORDER_STATUS_CONFIRM.getId())) {
                return CommResult.error("不能生成礼卡");
            }

            if (!order.getShippingStatus().equals(OrderShippingStatusEnum.SHIPPING_STATUS_UNSHIPPNG.getId())) {
                return CommResult.error("不能生成礼卡");
            }


            int affectCount = giftCardService.create(order);
            if (affectCount <= 0) {
                return CommResult.error();
            }
            return CommResult.success("创建"+String.valueOf(affectCount)+"张礼卡");

        } finally {
            if (key!=null) {
                redisHandler.unlock(key, value);
            }
        }
    }

    /**
     * 统计礼卡张数
     *
     * @return
     */
    @ApiOperation("统计礼卡张数")
    @PostMapping("/summary")
    public CommResult<Order> summary() {
        Map<String,Object> data = new HashMap<>();

        Member member = memberService.getCurrent();
        if (member==null) {
            data.put("mycount",0);
            data.put("rvcount",0);

            return CommResult.success(data);
        }

        Map<String,Object> params = new HashMap<>();

        params.put("memberId",member.getId());
        params.put("status",0);
        data.put("mycount",giftCardService.selectRowCount(params));

        params.clear();
        params.put("receiverId",member.getId());
        params.put("status",0);
        data.put("rvcount",giftCardService.selectRowCount(params));

        return CommResult.success(data);

    }


/*

    */
/**
     * 立即使用
     *
     * @param giftCardId
     * @return
     *//*

    @Log(desc = "立即使用", type = Log.LOG_TYPE.ADD)
    @ApiOperation("立即使用")
    @PostMapping("/useNow")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "giftCardId", value = "礼卡ID", dataType = "Long", paramType = "query")
    })
    public CommResult<GiftCard> useNow(Long giftCardId) {

        GiftCard giftCard = giftCardService.selectByPrimaryKey(giftCardId);
        Order order = giftCardService.build(giftCard);
        order = orderService.calculate(order);
        order.setPaymentVo(orderService.calculatePayment(order));
        Map<String,Object> data = new HashMap<>();
        data.put("order",order);
        data.put("shippingMethods",orderService.getShippingMethods(order));
        data.put("amount",order.getAmountPayable().subtract(order.calculatePaymentPaid()));
        if (order.getCouponCodeId()!=null) {
            CouponCode couponCode = couponCodeService.findById(order.getCouponCodeId());
            if (couponCode!=null) {
                data.put("couponCodeName",couponCode.getCoupon().getName());
            }
        }

        return CommResult.success(data);
    }

*/


    /**
     * 领取礼品卡
     *
     * @param giftCardId
     * @return
     */
    @Log(desc = "领取礼品卡", type = Log.LOG_TYPE.UPDATE)
    @ApiOperation("领取礼品卡")
    @PostMapping("/receiver")
    public CommResult<GiftCard> receiver(Long giftCardId) {

        Member member = memberService.getCurrent();
        GiftCard giftCard = giftCardService.selectByPrimaryKey(giftCardId);
        if (giftCard.getMemberId().equals(member.getId())) {
            return CommResult.error("不能领本人卡");
        }

        if (giftCard.getReceiverId()!=null) {
            return CommResult.error("已经被领取");
        }

        giftCard.setReceiverId(member.getId());
        giftCard.setStatus(1);

        giftCardService.updateByPrimaryKeySelective(giftCard);
        return CommResult.success(giftCard);
    }


    /**
     * 更新礼品卡
     *
     * @param giftCard
     * @return
     */
    @Log(desc = "更新礼品卡", type = Log.LOG_TYPE.UPDATE)
    @ApiOperation("更新礼品卡")
    @PostMapping("/update")
    public CommResult<GiftCard> update(@RequestBody GiftCard giftCard) {
        int affectCount = giftCardService.updateByPrimaryKeySelective(giftCard);
        if (affectCount <= 0){
            return CommResult.error();
        }
        GiftCard result = giftCardService.findById(giftCard.getId());
        return CommResult.success(result);
    }



}
